package whr.common.upload;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.ObjectMetadata;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import whr.common.utils.AliOssUtil;
import whr.common.utils.R;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

@RestController
@RequestMapping("file")
public class FileUpload {

    @Value("${web.upload-path}")
    private String uploadPath;

    private static final String LINUX_SERVER_IP = "192.168.0.18";
    private static final String LINUX_USERNAME = "root";
    private static final String LINUX_PASSWORD = "wds_2017";
    private static final String REMOTE_PATH = "/usr/local/wds_services/nginx/html/dist/202410181521/static/img/";
    @RequestMapping("/upload")
    public R upload( MultipartFile file, HttpServletRequest req) throws IOException {

        //本地上传
//        File folder = new File(uploadPath);
//        if (!folder.isDirectory()) {
//            folder.mkdirs();
//        }
//        // 对上传的文件重命名，避免文件重名
//        String oldName =  file.getOriginalFilename();
//        String newName = UUID.randomUUID().toString()
//                + oldName.substring(oldName.lastIndexOf("."), oldName.length());
//        //完整路径
//        String absolutionPath =  "http://localhost/202410181521/static/img/"+newName;
//        // 文件保存
////        file.transferTo(new File(folder, newName));
//
//
//        Path path = new File(uploadPath + newName).toPath();
//        // 将文件复制到Linux服务器上的指定路径
//        long copy = Files.copy(file.getInputStream(), path, StandardCopyOption.REPLACE_EXISTING);
//
//
//        // 返回上传文件的访问路径
////        String filePath = req.getScheme() + "://" + req.getServerName()
////                + ":" + req.getServerPort() +"/"  + newName + "?token=6915f4f1b4ba9efae3299ec7597643c3";
//        /*System.out.println("文件地址:"+ folder+newName);*/
//        R r =new R();
////        r.put("url",filePath);
//        r.put("assetsImg",absolutionPath);
//        r.put("copy",copy);



//        上传到Linux服务器
        try {
            JSch jsch = new JSch();
            Session session = jsch.getSession(LINUX_USERNAME, LINUX_SERVER_IP);
            session.setPassword(LINUX_PASSWORD);
            session.setConfig("StrictHostKeyChecking", "no");
            session.connect();

            Channel channel = session.openChannel("sftp");
            channel.connect();
            ChannelSftp sftpChannel = (ChannelSftp) channel;

            InputStream inputStream = file.getInputStream();
            sftpChannel.put(inputStream, REMOTE_PATH + file.getOriginalFilename());

            sftpChannel.disconnect();
            channel.disconnect();
            session.disconnect();
            String absolutionPath =  "http://192.168.0.18/202410181521/static/img/"+file.getOriginalFilename();
            R r =new R();
//            r.put("url",filePath);
            r.put("assetsImg",absolutionPath);
//            r.put("copy",copy);
            return r;
        } catch (Exception e) {
            e.printStackTrace();
            return R.error();
        }


//        return r;
    }

    // 引入oss工具类
    @Autowired
    private AliOssUtil aliOssUtil;

    @RequestMapping("/upload2")
    public R upload2( MultipartFile file){

        try {
            // 获取文件的名称
            String originalFilename = file.getOriginalFilename();
            // 截取文件的后缀名
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            // 生成新的文件名
            String newFileName = UUID.randomUUID().toString() + suffix;

            // 文件的请求路径
            String filePath = aliOssUtil.upload(file.getBytes(), newFileName);
            return R.ok(filePath);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return R.error("文件上传失败");

    }

    //头像上传到本地服务器
    @RequestMapping("/upload3")
    public R upload3( MultipartFile file, HttpServletRequest req) throws IOException {
        File folder = new File(uploadPath);
        if (!folder.isDirectory()) {
            folder.mkdirs();
        }
        String oldName =  file.getOriginalFilename();
        String newName = UUID.randomUUID().toString()
                + oldName.substring(oldName.lastIndexOf("."), oldName.length());
        String absolutionPath =newName;


        Path path = new File(uploadPath + newName).toPath();
        // 将文件复制到Linux服务器上的指定路径
        long copy = Files.copy(file.getInputStream(), path, StandardCopyOption.REPLACE_EXISTING);
        // 返回上传文件的访问路径

        R r =new R();

        r.put("assetsImg",absolutionPath);
        r.put("copy",copy);
        return r;
    }
    // 阿里云OSS
    //域名
    public static final String ALI_DOMAIN = "https://liuli-manage.oss-cn-chengdu.aliyuncs.com/";


    @RequestMapping("/upload4")
    public R upload4(MultipartFile file, HttpServletRequest req) throws IOException, NoSuchAlgorithmException {
        // 计算文件的哈希值
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] buffer = new byte[8192];
        int bytesRead;
        try (InputStream fis = file.getInputStream()) {
            while ((bytesRead = fis.read(buffer))!= -1) {
                md.update(buffer, 0, bytesRead);
            }
        }
        byte[] digest = md.digest();
        StringBuilder sb = new StringBuilder();
        for (byte b : digest) {
            sb.append(String.format("%02x", b));
        }
        String fileHash = sb.toString()+".jpg";

        String endpoint = "http://oss-cn-chengdu.aliyuncs.com";
        String accessKeyId = "LTAI5tBLssJNsZ9SNjJf3x2k";
        String accessKeySecret = "S74v16e897S2V4bqeFVXd2XUrlNRnV";
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        boolean exists = ossClient.doesObjectExist("liuli-manage", fileHash);
        if (!exists) {
            try (InputStream is = file.getInputStream()) {
                byte[] data = new byte[is.available()];
                is.read(data);
                ObjectMetadata metadata = new ObjectMetadata();
                metadata.setContentLength(file.getSize());
                ossClient.putObject("liuli-manage", fileHash, new ByteArrayInputStream(data), metadata);
            }
        }
        ossClient.shutdown();
        R r = new R();
        r.put("assetsImg", ALI_DOMAIN+fileHash);
        return R.ok(r);
    }
    // pdf文件
    @RequestMapping("/upload5")
    public R upload5(MultipartFile file, HttpServletRequest req) throws IOException, NoSuchAlgorithmException {
        // 计算文件的哈希值
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] buffer = new byte[8192];
        int bytesRead;
        try (InputStream fis = file.getInputStream()) {
            while ((bytesRead = fis.read(buffer))!= -1) {
                md.update(buffer, 0, bytesRead);
            }
        }
        byte[] digest = md.digest();
        StringBuilder sb = new StringBuilder();
        for (byte b : digest) {
            sb.append(String.format("%02x", b));
        }
        String fileHash = sb.toString()+".pdf";

        String endpoint = "http://oss-cn-chengdu.aliyuncs.com";
        String accessKeyId = "LTAI5tBLssJNsZ9SNjJf3x2k";
        String accessKeySecret = "S74v16e897S2V4bqeFVXd2XUrlNRnV";
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        boolean exists = ossClient.doesObjectExist("liuli-manage", fileHash);
        if (!exists) {
            try (InputStream is = file.getInputStream()) {
                byte[] data = new byte[is.available()];
                is.read(data);
                ObjectMetadata metadata = new ObjectMetadata();
                metadata.setContentLength(file.getSize());
                ossClient.putObject("liuli-manage", fileHash, new ByteArrayInputStream(data), metadata);
            }
        }
        ossClient.shutdown();
        R r = new R();
        r.put("assetsImg", ALI_DOMAIN+fileHash);
        return R.ok(r);
    }
}
